#!/bin/sh

JS_STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E "(\.vue|\.jsx?)$")
SCSS_STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM | grep -E "(\.vue|\.p?css)$")

if [[ "$JS_STAGED_FILES" = "" && "$SCSS_STAGED_FILES" = "" ]]; then
  exit 0
fi

PASS=true

# Check for felint
which felint &> /dev/null
if [[ "$?" == 1 ]]; then
  if [ -f ~/.zshrc ]; then
    source ~/.zshrc
  elif [ -f ~/.bash_profile ]; then
    source ~/.bash_profile
  fi
fi

if [[ "$JS_STAGED_FILES" != "" ]]; then
  echo "\nValidating Javascript:\n"

  felint lintjs --exitcode $JS_STAGED_FILES

  if [[ "$?" == 0 ]]; then
    echo "\033[32mESLint Passed\033[0m"
  else
    echo "\033[41mESLint Failed\033[0m"
    PASS=false
  fi

  echo "\nJavascript validation completed!\n"
fi


if [[ "$SCSS_STAGED_FILES" != "" ]]; then
  echo "\nValidating css:\n"

  felint lintcss --exitcode $SCSS_STAGED_FILES

  if [[ "$?" == 0 ]]; then
    echo "\033[32mstylelint Passed\033[0m"
  else
    echo "\033[41mstylelint Failed\033[0m"
    PASS=false
  fi

  echo "\ncss validation completed!\n"
fi

if ! $PASS; then
  echo "\033[41mCOMMIT FAILED:\033[0m Your commit contains files that should pass ESLint and stylelint but do not. Please fix the ESLint and stylelint errors and try again.\n"
  exit 1
else
  echo "\033[42mCOMMIT SUCCEEDED\033[0m\n"
fi

exit $?
